<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">

<head>
    <th:block th:include="include :: header('新增模板')" />
    <th:block th:include="include :: oly_jsoneditor_css" />
    <th:block th:include="include :: oly_markdown_css" />
    <th:block th:include="include :: bootstrap-fileinput-css" />
    <style>
        .tData {
            display: none;
        }
        .tHtml{
         opacity: 0;
        }
   </style>
</head>

<body class="white-bg" th:object="${olyTemplate}">
    <div class="modal inmodal fade" id="myModal6" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span
                            aria-hidden="true">&times;</span><span class="sr-only">Close</span>
                    </button>
                    <h4 class="modal-title">模板预览</h4>
                </div>
                <div class="modal-body" id="htmlView">

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-white" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-template-add">
            <input name="templateId" th:field="*{templateId}" type="hidden">
            <input name="templateUrl" th:field="*{templateUrl}" type="hidden">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">父模板：</label>
                <div class="col-sm-8">
                    <div class="input-group">
                        <input id="treeId" name="parentId" type="hidden" th:value="${olyTemplate?.templateId}" />
                        <input class="form-control" type="text" onclick="selectTemplateTree()" id="treeName"
                            readonly="true" th:value="*{templateName}" required>
                        <span class="input-group-addon"><i class="fa fa-search"></i></span>
                    </div>
                </div>
            </div>


            <div class="form-group">
                <label class="col-sm-3 control-label is-required">模板类型：</label>
                <div class="col-sm-8">
                    <div class="radio-box" th:each="dict : ${@dictTag.getType('oly_template_type')}">
                        <input type="radio" th:id="${dict.dictCode}" th:value="${dict.dictValue}" name="templateType"
                            th:field="*{templateType}">
                        <label th:for="${dict.dictCode}" th:text="${dict.dictLabel}"></label>
                    </div>
                </div>
            </div>

            <div class="form-group">
                <label class="col-sm-3 control-label is-required">模板名：</label>
                <div class="col-sm-8">
                    <input name="templateName" required minlength="2" maxlength="16" class="form-control" type="text">
                </div>
            </div>

            <div class="form-group tUp tr">
                <label class="col-sm-3 control-label">上传模板：</label>
                <div class="col-sm-8">
                    <input name="file" class="form-control" type="file">
                    <br>
                    <input name="templateUrl" class="form-control" disabled type="text">
                </div>
            </div>


            <div class="form-group tHtml tr">
                <label class="col-sm-3 control-label">模板内容：</label>
                <div class="col-sm-8">
                    <div class="tin-box">   
                        <textarea id="foHtmlContent">
    
    
                        </textarea>
                    </div>  
                        <div id="coHtmlContent">
                            <textarea style="display:none;"></textarea>
                        </div>
                </div>
            </div>

            <div class="form-group tData tr">
                <label class="col-sm-3 control-label">模板数据：</label>
                <div class="col-sm-8">
                    <div id="templateParam" class="json-editor"></div>
                </div>
            </div>

            <div class="form-group">
                <label class="col-sm-3 control-label is-required">模板状态：</label>
                <div class="col-sm-8">
                    <div class="radio-box" th:each="dict : ${@dictTag.getType('oly_template_visible')}">
                        <input type="radio" th:id="${dict.dictCode}" name="visible" th:value="${dict.dictValue}"
                            th:checked="${dict.default}">
                        <label th:for="${dict.dictCode}" th:text="${dict.dictLabel}"></label>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">是否内置：</label>
                <div class="col-sm-8">
                    <div class="radio-box">
                        <input type="radio" checked id="tYes" name="built" value="1" th:field="*{built}">
                        <label for="tYes">是</label>
                    </div>
                    <div class="radio-box">
                        <input type="radio" id="tNo" name="built" value="0" th:field="*{built}">
                        <label for="tNo">否</label>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">显示顺序：</label>
                <div class="col-sm-8">
                    <input name="orderNum" class="form-control" type="number" required>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">备注：</label>
                <div class="col-sm-8">
                    <textarea name="remark" class="form-control">
                    </textarea>
                </div>
            </div>
            <div class="form-group">
                <a class="btn btn-success" onclick="submitHandler()">
                    <i class="fa fa-plus"></i> 添加
                </a>
                <a class="btn btn-success" onclick="okView()" data-toggle="modal" id="viewBtn" data-target="#myModal6">
                    <i class="fa fa-eye"></i> 预览
                </a>

            </div>
        </form>
    </div>
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: oly_tinymce" />
    <th:block th:include="include :: oly_jsoneditor_js" />
    <th:block th:include="include :: oly_markdown_js" />
    <th:block th:include="include :: bootstrap-fileinput-js" />
    <script th:inline="javascript">
        var prefix = ctx + "oly/template";
        var supportSuffix = "pdf,excel,html,jpg"
        $("#form-template-add").validate({
            onkeyup: false,
            rules: {
                templateType: {
                    required: true
                },
                templateName: {
                    required: true,
                    rangelength: [2, 16],
                },
                orderNum: {
                    digits: true
                },
                visible: {
                    required: true
                },
                built: {
                    required: true
                }
            },
            messages: {
                "templateName": {
                    remote: "名称不能为空"
                }
            },
            focusCleanup: true
        });

        function submitHandler() {
            if ($.validate.form()) {
                var data = $('#form-template-add').serializeArray();
                data.push({ "name": "templateHtml", "value": getHtml() });
                data.push({ "name": "templateParam", "value": JSON.stringify(jaonEditor.get(), null, 2) });
                $.operate.saveTab(prefix + "/add", data);
            }
        }
        $("input[name='templateType']").on('ifChecked', function (event) {
            changeBox();
        });

        var coEditor = editormd("coHtmlContent", {
            width: "100%",
            height: 720,
            watch: false,
            toolbar: false,
            codeFold: true,
            searchReplace: true,
            placeholder: "Enjoy coding!",
            value: '',
            theme: "dark",
            mode: "text/html",
            path: '/ajax/libs/oly_markdown/lib/'
        });

        tinymce.init({
			selector: '#foHtmlContent',
			language: 'zh-Hans',
			height: 800,
			plugins: 'preview powerpaste casechange importcss searchreplace autolink autosave save directionality code visualblocks visualchars fullscreen image link media codesample table charmap pagebreak nonbreaking anchor tableofcontents insertdatetime advlist lists checklist wordcount a11ychecker editimage help formatpainter permanentpen pageembed charmap mentions quickbars  emoticons advtable export',
			toolbar: 'undo redo tableofcontents | bold italic underline strikethrough | fontfamily fontsize blocks | alignleft aligncenter alignright alignjustify | outdent indent |  numlist bullist checklist | forecolor backcolor casechange permanentpen formatpainter removeformat | pagebreak | charmap emoticons | fullscreen  preview save print | insertfile image media pageembed link anchor codesample | a11ycheck ltr rtl |',
			images_file_types: 'jpg, jpeg, gif,png,bmp,webp',
			tableofcontents_class: 'markdown-toc',
			content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:16px }',
			images_upload_url: ctx + "oly/oss/upload/code/location/msg",
			images_upload_credentials: true
		});
        


        /*olyTemplateType
       0：为目录  目录 目录名 备注 用途
       1：自定义html 多数据
       2：以上需要上传 不支持修改*/
       function changeBox() {
        $("#form-template-add").show();
            let tType = $("input[name='templateType']:checked").val()
            $("#viewBtn").hide();
            $(".tox").hide();
            $("#coHtmlContent").hide();
            if (tType == 0) {
                $(".tr").hide();
            }
            else if (tType == 1) {
                $(".tHtml").show();
                $(".tUp").hide();
                $(".tData").hide();
                $(".tox").show();
            }
            else if (tType == 2) {
                $(".tHtml").show();
                $(".tData").show();
                $(".tUp").hide();
                $("#coHtmlContent").show();
                $("#viewBtn").show();

            }
            else {
                $(".tHtml").hide();
                $(".tData").hide();
                $(".tUp").show();
            }
        }
        setTimeout(() => {
            changeBox();
            $(".tHtml").css("opacity",1);
        }, 1000);
        function getHtml() {
            if ($("input[name='templateType']:checked").val() == 1) {
              return tinyMCE.activeEditor.getContent();
            } else {
                return coEditor.getValue();
            }
        }
        /*模板模型-新增-选择父树*/
        function selectTemplateTree() {
            var options = {
                title: '模板模型选择',
                width: "380",
                url: prefix + "/selectTemplateTree/" + $("#treeId").val(),
                callBack: doSubmit
            };
            $.modal.openOptions(options);
        }

        function doSubmit(index, layero) {
            var body = $.modal.getChildFrame(index);
            $("#treeId").val(body.find('#treeId').val());
            $("#treeName").val(body.find('#treeName').val());
            $.modal.close(index);
        }

        const json =
        {

        };

        const options = {
            mode: 'tree',
            modes: ['code', 'form', 'text', 'tree', 'view', 'preview'], // allowed modes
            onError: function (err) {
                alert(err.toString())
            },
            onModeChange: function (newMode, oldMode) {
                console.log('Mode switched from', oldMode, 'to', newMode)
            },
            templates: [
                {
                    text: 'Person',
                    title: 'Insert a Person Node',
                    className: 'jsoneditor-type-object',
                    field: 'PersonTemplate',
                    value: {
                        'firstName': 'John',
                        'lastName': 'Do',
                        'age': 28
                    }
                },
                {
                    text: 'Address',
                    title: 'Insert a Address Node',
                    field: 'AddressTemplate',
                    value: {
                        'street': '',
                        'city': '',
                        'state': '',
                        'ZIP code': ''
                    }
                }
            ]
        }
        // create the editor
        const container = document.getElementById('templateParam');
        const jaonEditor = new JSONEditor(container, options, json);
        jaonEditor.expandAll();

        function okView() {
            let data = jaonEditor.get();
            data.content = getHtml();
            $.post(prefix + "/example", data, function (res) {
                $("#htmlView").empty();
                $("#htmlView").append(res);
            })
        }
        $(document).ready(function () {
            $("input[name='file']").fileinput({
                rtl: true,
                showPreview: false, //是否显示预览
                hideThumbnailContent: true,//是否在缩略图中隐藏预览内容（图像，pdf内容，文本内容等）。
                uploadUrl: prefix + "/templateUpload",
                allowedFileExtensions: supportSuffix.split(",")
            });
            $("input[name='file']").on("fileuploaded", function (event, data, previewId, index) {
                $("input[name='templateUrl']").val(data.response.data.msg);
            })
        });

    </script>

</body>

</html>